package com.selly.hanjuang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;

import com.selly.hanjuang.lib.JSONParser;
import com.selly.hanjuang.lib.ListAdapterCart;
import com.selly.hanjuang.lib.MyApplication;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class MenuCart extends Activity {

	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> DaftarProduk;

	String indexDeleteList = "";
	String indexUpdateList = "";
	
	public static final String TAG_DELETE= "indeks_delete";
	public static final String TAG_UPDATE= "indeks_update";

	// url http://hanjuang.0fees.net/daftar_produk.php
	// private static String url_daftar_produk =
	// "http://10.162.69.177/hanjuang/json/daftar_cart.php";

	// JSON Node names
	/*
	 * public static final String TAG_SUCCESS = "success"; public static final
	 * String TAG_DAFTAR_PRODUK = "daftar_cart"; public static final String
	 * TAG_ID_PRODUK = "id_produk"; public static final String TAG_NAMA_PRODUK =
	 * "nama_produk"; public static final String TAG_LINK_IMAGE_PRODUK =
	 * "link_image"; public static final String TAG_KOMPOSISI = "komposisi";
	 * public static final String TAG_HARGA = "harga";
	 */

	// Button ButtonAddTocart;

	// daftar_produk JSONArray
	// JSONArray daftar_produk = null;
	ArrayList<Bandrek> bandrekList = null;

	ListView list;
	TextView txtGrandTotal;
	ImageButton btnNext;
	
	ListAdapterCart adapter;
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu_cart);

		// get cikan
		String msg = ((MyApplication) this.getApplication()).getStringValue();
		Log.i("INFO MyApplication", msg);

		// Hashmap for ListView
		DaftarProduk = new ArrayList<HashMap<String, String>>();

		bandrekList = ((MyApplication) this.getApplication()).getBandrekList();

		// detail produk from intent
		Intent i = getIntent();

		// getting id_produk from intent
		Log.d("cikan getextra 2", indexDeleteList);
		indexDeleteList= i.getStringExtra(TAG_DELETE);
		if (indexDeleteList != null) {
			Log.d("cikan getextra 1", indexDeleteList);
			bandrekList.remove(Integer.parseInt(indexDeleteList));
		}
		
		//Log.d("naha??", "bla bla bla");

		// loading daftar
		new LoadDaftarCartActivity().execute();
		
		txtGrandTotal = (TextView) findViewById(R.id.txtGrandTotal);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent("com.selly.hanjuang.NewOrderActivity"));
			}
		});
		
		// Get listview
		list = (ListView) findViewById(R.id.list);

		// on selecting single rumah sakit
		// launching detail rumah sakit layout
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected listitem
				//String id_produk = ((TextView) view .findViewById(R.id.id_produk)).getText().toString();

				// Starting new intent
				// Intent in = new Intent(getApplicationContext(),
				// DetailProductActivity.class);
				// sending id_produk to next activity : DetailBarangActivity
				// in.putExtra(TAG_ID_PRODUK, id_produk);

				// startActivityForResult(in, 100);
			}
		});

		// btnEdit = (ImageButton) findViewById(R.id.btnEdit);

		// ImageButton btnTentangAplikasi = (ImageButton)
		// findViewById(R.id.btnaplikasi);
		// btnTentangAplikasi.setOnClickListener(this);

		// btnEdit.setOnClickListener(this);
		
	}

	/**
	 * Updating parsed JSON data into ListView
	 * */
	public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
		adapter = new ListAdapterCart(this, daftar);
		list.setAdapter(adapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received
			// means user edited/deleted record
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}
	}

	/**
	 * Background Async Task to Load all record data by making HTTP Request
	 * */
	class LoadDaftarCartActivity extends
			AsyncTask<String, String, String> {

		/**
		 * Before starting background thread show progress dialog
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(MenuCart.this);
			pDialog.setMessage("Mohon tunggu yah ;)");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting all record data from url
		 */
		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub

			// Building Parameters
			//List<NameValuePair> params = new ArrayList<NameValuePair>();

			// getting JSON string from URL
			/*
			 * JSONObject json = jParser.makeHttpRequest(url_daftar_produk,
			 * "GET", params);
			 */

			// check your log cat for JSON response
			// Log.d("Daftar Rumah Sakit Coy!:", json.toString());

			// try {
			// Checking for SUCCESS TAG
			// int success = json.getInt(TAG_SUCCESS);

			// if (success == 1) {
			// Ada record Data (SUCCESS = 1)
			// Getting Array of daftar_produk
			// daftar_produk = json.getJSONArray(TAG_DAFTAR_PRODUK);
			// bandrekList = ((MyApplication)
			// this.getApplication()).getBandrekList();

			// Looping through All daftar_produk
			for (int i = 0; i < bandrekList.size(); i++) {
				// JSONObject c = daftar_produk.getJSONObject(i);

				// Storing each json item in variable
				// String id_produk = c.getString(TAG_ID_PRODUK);
				// String nama_produk = c.getString(TAG_NAMA_PRODUK);
				// String link_image_produk = c.getString(TAG_LINK_IMAGE_PRODUK);

				// String komposisi = c.getString(TAG_KOMPOSISI);
				// String harga = c.getString(TAG_HARGA);

				// creating new HashMap
				HashMap<String, String> map = new HashMap<String, String>();

				// adding each child node to HashMap key => value
				// map.put(TAG_ID_PRODUK, id_produk);
				// map.put(TAG_NAMA_PRODUK, nama_produk);
				// map.put(TAG_LINK_IMAGE_PRODUK, link_image_produk);
				// map.put(TAG_KOMPOSISI, komposisi);
				// map.put(TAG_HARGA, harga);

				map.put("id_produk", bandrekList.get(i).getId_product());
				map.put("nama_produk", bandrekList.get(i).getNama_product());
				map.put("harga", String.valueOf(bandrekList.get(i).getHarga()));
				map.put("qty", String.valueOf(bandrekList.get(i).getQty()));
				map.put("totalHarga", String.valueOf(bandrekList.get(i).getTotalHarga()));
				//map.put("harga", String.valueOf(bandrekList.get(i).getHarga()));
				map.put("link_image", bandrekList.get(i).getLink_image());

				// adding HashList to ArrayList
				DaftarProduk.add(map);
			}
			// } else {
			// Tidak ada record data (success = 0)
			// akan menutup aplikasi
			// finish();
			// }
			// } catch (JSONException e) {
			// e.printStackTrace();
			// }

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 */
		@Override
		protected void onPostExecute(String file_url) {
			// TODO Auto-generated method stub
			// super.onPostExecute(file_url);
			// dismiss the dialog after getting all record rumah sakit
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					// updating listview
					SetListViewAdapter(DaftarProduk);
					hitungGrandtotal();
				}
			});
		}
	}

	/* Initiating Menu XML file (menu_context.xml) */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_context, menu);
		return true;
	}

	/**
	 * Event Handling for Individual menu item selected Identify single menu
	 * item by it's id
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.menu_view_cart:
			// Single menu item is selected do something
			// Ex: launching new activity/screen or show alert message
			// Toast.makeText(MenuAwal.this, "Bookmark is Selected",
			// Toast.LENGTH_SHORT).show();
			startActivity(new Intent("com.selly.hanjuang.NewOrderActivity"));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent a = new Intent(this, MenuTransaksi.class);
			a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(a);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/*
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub switch (v.getId()) { case R.id.btnEdit:
	 * //v.startAnimation(animAlpha); //startActivity(new
	 * Intent("com.selly.hanjuang.MENUPEMESANAN")); Log.i("test button",
	 * "cooooy button :D"); break; } }
	 */
	
	public void hitungGrandtotal(){
		int grand = 
				((MyApplication) this.getApplication()).getGrandTotal();
		//String sGrand = "123";
		txtGrandTotal.setText("Rp " + grand);
	}

}
